<template>
  <div class="sub-menu">
    <menu-item show-collapse :menu="menu" v-model:expand="visible" :level="level" />
    <b-collapse-transition v-if="menu.children.length > 0">
      <div class="sub-child" v-show="visible">
        <template v-for="(child, childIndex) in menu.children" :key="childIndex">
          <menu-item v-if="!child.children" :menu="child" :level="level + 1" />
          <submenu v-else :opens="opens" :menu="child" :level="level + 1" />
        </template>
      </div>
    </b-collapse-transition>
  </div>
</template>

<script>
import { ref, inject } from 'vue'
import MenuItem from './menu-item.vue'

export default {
  name: 'Submenu',
  components: { MenuItem },
  props: {
    menu: {
      type: Object,
      default: () => ({}),
    },
    level: {
      type: Number,
      default: 0,
    },
    opens: {
      type: Array,
      default: () => [],
    },
  },
  setup(props) {
    const visible = ref(props.opens.includes(props.menu.nodeKey))
    const MenuEmitter = inject('MenuEmitter', {})

    if (MenuEmitter.emitter) {
      MenuEmitter.emitter.on('collapseAll', val => (visible.value = !val))
    }

    return { visible }
  },
}
</script>
